package org.dce.screencapturer.actions.objects;

import java.awt.Component;
import java.awt.Font;
import java.awt.GraphicsEnvironment;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;

import org.dce.screencapturer.actions.DropDownAction;
import org.dce.screencapturer.objects.DrawingObject;
import org.dce.screencapturer.objects.ShapeObject;
import org.dce.screencapturer.objects.TextAttributes;
import org.dce.screencapturer.util.IconFactory;

@SuppressWarnings("serial")
public class SelectFontAction extends DropDownAction {
	
	private static String[] fontNames = null;

	public SelectFontAction() {
		super("categories.text", "actions.selectFont", IconFactory.getIcon("/images/font.png"));
		
		DefaultListModel model = new DefaultListModel();
		for (String fontName:getFontNames()){
			model.addElement(fontName);
		}
		setModel(model);
		setRenderer(new FontRenderer());
	}
	
	private String[] getFontNames(){
		if (fontNames == null){
			fontNames = GraphicsEnvironment
			.getLocalGraphicsEnvironment()
			.getAvailableFontFamilyNames();
		}
		
		return fontNames;
	}

	@Override
	protected void itemSelected(Object object) {
		
		ShapeObject shapeObject = (ShapeObject)getObject();
		
		TextAttributes textAttributes = (TextAttributes) shapeObject.getTextAttributes().clone();
		
		Font currentFont = textAttributes.getFont();
		
		Font font = new Font((String)object,currentFont.getStyle(),currentFont.getSize());
		
		textAttributes.setFont(font);
		
		shapeObject.setTextAttributes(textAttributes);
		
		System.out.println(object);
	}

	private class FontRenderer 
		extends DefaultListCellRenderer {

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {

			Component component = super.getListCellRendererComponent(list, value, index, isSelected,
					cellHasFocus);
			
			String fontName = (String)value;
			
			component.setFont(new Font(fontName,Font.PLAIN,16));
			
			return component;
		}
		
	}
	

	@Override
	protected boolean acceptObject(DrawingObject anObject) {
		return anObject instanceof ShapeObject;
	}
}
